package zx.x.modules.app.pw;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import org.joda.time.LocalDateTime;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import zx.x.common.utils.R;
import zx.x.modules.app.entity.OrderEntity;
import zx.x.modules.app.entity.OrderJobLogEntity;
import zx.x.modules.app.entity.SysOrderLogEntity;
import zx.x.modules.app.service.OrderService;
import zx.x.modules.app.service.SysOrderLogService;

import java.time.LocalDate;
import java.util.List;

/**
 * xu
 **/
@Component
public class pw {


    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SysOrderLogService sysOrderLogService;


    //账号(测试)
    public static final String AC = "70910851";
//    public static final String AC = "6061268";
    //密码(测试)
    public static final String PW = "ea42cdd445996be2b7dbe814a06692f9";
//    public static final String PW = "a6a2b348145d17589a3abfa039bcb4ce";
    public static final String PFT_URL = "http://open.12301.cc/openService/pftMX.php";// 正式地址
//    public static final String PFT_URL = "http://open.12301dev.com/openService/pftMX.php";// 测试地址  上线需要变更为正式地址  正式地址 http://open.12301.cc/openService/pftMX.php
//    public static final String LID = "153363";
//    public static final String M = "3264683";


    /**
     * 门票列表
     */
    @RequestMapping("/ticket")
    public String ticket() {
        PFTOrderSubmitRequestEntity pftOrderSubmitRequestEntity = new PFTOrderSubmitRequestEntity();
        PFTOrderSubmitBody pftOrderSubmitBody = new PFTOrderSubmitBody();
        Ticket ticket = new Ticket();
        ticket.setAc(AC);
        ticket.setPw(PW);
        //这里是景区id
        ticket.setN("153363");
        //这里是门票id
        ticket.setM("495815");
        pftOrderSubmitBody.setTicket(ticket);
        pftOrderSubmitRequestEntity.setBody(pftOrderSubmitBody);
        String strXml = JAXBXmlUtil.convertToXml(pftOrderSubmitRequestEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(PFT_URL, formEntity, String.class);
        System.out.println("最初原始数据:" + result);
        String pftOrderSubmitDataResultXml = getPftResultXml(result, "ns1:Get_Ticket_ListResponse", "Get_Ticket_List");
        String productData = XML.toJSONObject(pftOrderSubmitDataResultXml).toString();
        com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(productData);
        Object data = parseObject.get("Data");
        com.alibaba.fastjson.JSONObject object = JSON.parseObject(JSON.toJSONString(data));
        Object rec = object.get("Rec");
        TicketResponse response = JSON.parseObject(JSON.toJSONString(rec), TicketResponse.class);
        System.out.println("转换成对象的门票信息：" + JSON.toJSONString(response));
        //xml数据已经转换成类 直接进行业务就可以了

        return "success";
    }


    /**
     * 产品列表
     */
    @RequestMapping("/product")
    public String product() {
        PFTOrderSubmitRequestEntity pftOrderSubmitRequestEntity = new PFTOrderSubmitRequestEntity();
        PFTOrderSubmitBody pftOrderSubmitBody = new PFTOrderSubmitBody();
        Product product = new Product();
        product.setAc(AC);
        product.setPw(PW);
        //相当于分页的开始
        product.setN("0");
        //相当于分页的结束
        product.setM("100");
        pftOrderSubmitBody.setProduct(product);
        pftOrderSubmitRequestEntity.setBody(pftOrderSubmitBody);
        String strXml = JAXBXmlUtil.convertToXml(pftOrderSubmitRequestEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(PFT_URL, formEntity, String.class);
        System.out.println("最初原始数据:" + result);
        String pftOrderSubmitDataResultXml = getPftResultXml(result, "ns1:Get_ScenicSpot_ListResponse", "Get_ScenicSpot_List");
        String productData = XML.toJSONObject(pftOrderSubmitDataResultXml).toString();
        com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(productData);
        Object data = parseObject.get("Data");
        com.alibaba.fastjson.JSONObject object = JSON.parseObject(JSON.toJSONString(data));
        Object rec = object.get("Rec");
        String s = JSON.toJSONString(rec);
        if (s.contains("[")) {
            List<ProductInformation> array = JSON.parseArray(s, ProductInformation.class);
            //xml数据已经转换成类 直接进行业务就可以了 多个产品的处理
        } else {
            ProductInformation information = JSON.parseObject(s, ProductInformation.class);
            //xml数据已经转换成类 直接进行业务就可以了 单个产品的处理
        }

        return "success";
    }


    /**
     * 产品详情
     */
    @RequestMapping("/product/details")
    public String productDetails() {
        PFTOrderSubmitRequestEntity pftOrderSubmitRequestEntity = new PFTOrderSubmitRequestEntity();
        PFTOrderSubmitBody pftOrderSubmitBody = new PFTOrderSubmitBody();
        ProductDetails productDetails = new ProductDetails();
        productDetails.setAc(AC);
        productDetails.setPw(PW);
        //这里是景区id 应该就是产品id
        productDetails.setN("153363");
        pftOrderSubmitBody.setProductDetails(productDetails);
        pftOrderSubmitRequestEntity.setBody(pftOrderSubmitBody);
        String strXml = JAXBXmlUtil.convertToXml(pftOrderSubmitRequestEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(PFT_URL, formEntity, String.class);
        System.out.println("最初原始数据:" + result);
        String p = getPftResultXml(result, "ns1:Get_ScenicSpot_InfoResponse", "Get_ScenicSpot_Info");
        String productData = XML.toJSONObject(p).toString();
        ProductDetailsCheckDataResult json = JSONUtil.jsonToObject(productData, ProductDetailsCheckDataResult.class);
        System.out.println("产品详情转换为对象的数据:" + JSON.toJSONString(json));
        //xml数据已经转换成类 直接进行业务就可以了

        return "success";
    }


    //提交订单
   /* @GetMapping("notToken")
    @ApiOperation("忽略Token验证测试")*/
    public R savePwtOrder(Card card) {

//        card.setOtherSysProductId("495815");

        LocalDateTime ldt = LocalDateTime.now();
        card.setValidTime(ldt);
        card.setExpiryTime(ldt);

        PFTOrderSubmitRequestEntity pftOrderSubmitRequestEntity = new PFTOrderSubmitRequestEntity();
        PFTOrderSubmitBody pftOrderSubmitBody = new PFTOrderSubmitBody();
        PFTOrderSubmit pftOrderSubmit = new PFTOrderSubmit();
        pftOrderSubmit.setAc(AC);
        pftOrderSubmit.setPw(PW);
        pftOrderSubmit.setLid(card.getLID());
        pftOrderSubmit.setTid(card.getOtherSysProductId());
        pftOrderSubmit.setRemotenum(card.getId().toString());
        pftOrderSubmit.setTnum(card.getSl());
        LocalDate now = LocalDate.now();
        pftOrderSubmit.setPlaytime(now.toString());
        //
//        if(now.isAfter(card.getValidTime().toLocalDate())){
//            pftOrderSubmit.setPlaytime(now.toString());
//        } else {
//            pftOrderSubmit.setPlaytime(card.getValidTime().toLocalDate().toString());
//        }
        pftOrderSubmit.setOrdername("特惠票");
        if (card.getIdCardNo() != null) {
            pftOrderSubmit.setOrdername(card.getIdCardName());
            pftOrderSubmit.setPersonID(card.getIdCardNo());
        }
        pftOrderSubmit.setOrdertel(card.getUserTel());
        pftOrderSubmit.setSmsSend("0");
        pftOrderSubmit.setPaymode("2");
        pftOrderSubmit.setOrdermode("0");
        pftOrderSubmit.setConcatID("0");
        pftOrderSubmit.setPCode("0");
        pftOrderSubmit.setM(card.getM());
        pftOrderSubmitBody.setPftOrderSubmit(pftOrderSubmit);
        pftOrderSubmitRequestEntity.setBody(pftOrderSubmitBody);
        String strXml = JAXBXmlUtil.convertToXml(pftOrderSubmitRequestEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(PFT_URL, formEntity, String.class);
        System.out.println("pft orderPreCheck result:" + result);
        String pftOrderSubmitDataResultXml = getPftResultXml(result, "ns1:PFT_Order_SubmitResponse", "PFT_Order_Submit");
        String pftOrderSubmitDataResultJson = XML.toJSONObject(pftOrderSubmitDataResultXml).toString();
        PFTOrderSubmitDataResult pftOrderSubmitDataResult = JSONUtil.jsonToObject(pftOrderSubmitDataResultJson, PFTOrderSubmitDataResult.class);
        System.out.println("解析完的数据：" + JSON.toJSONString(pftOrderSubmitDataResult));
        if (pftOrderSubmitDataResult.getData().getRec().getUuerrorcode() == null) {
            card.setSupplierOrderId(pftOrderSubmitDataResult.getData().getRec().getUuordernum());
            card.setPunchTicketNo(pftOrderSubmitDataResult.getData().getRec().getUucode());
            String ewm = JSON.toJSONString(pftOrderSubmitDataResult.getData().getRec().getUuqrcodeimg());
            String uuOrderNum = JSON.toJSONString(pftOrderSubmitDataResult.getData().getRec().getUuordernum());
            //处理二维码
            OrderEntity o = new OrderEntity();
            o.setId(Math.toIntExact(card.getId()));
            o.setZt(12L);
            o.setEwm(ewm.replaceAll("\"", ""));
            o.setUordernum(uuOrderNum.replaceAll("\"", ""));// 票务通订单号
            orderService.updateById(o);

            SysOrderLogEntity oLog = new SysOrderLogEntity();
            oLog.setOId(o.getId());
            oLog.setLogText("成功出票");
            oLog.setZt(13);
            sysOrderLogService.save(oLog);
        } else {
            //1075表示已下单
            if ("1075".equals(pftOrderSubmitDataResult.getData().getRec().getUuerrorcode())) {
                card.setSupplierOrderId(pftOrderSubmitDataResult.getData().getRec().getUuordernum());
                card.setPunchTicketNo(pftOrderSubmitDataResult.getData().getRec().getUucode());
                //cardService.update(card);
            } else {
                card.setSupplierOrderId(pftOrderSubmitDataResult.getData().getRec().getUuerrorinfo());
                //处理本系统的业务
            }
            //创建订单失败打印信息
            System.out.println("pft orderPreCheck result fail" + pftOrderSubmitDataResult.getData().getRec());
        }


        return R.ok().put("msg", "无需token也能访问。。。");
    }

    public static String getPftResultXml(String result, String methodResponse, String method) {
        JSONObject xmlJSONObj = XML.toJSONObject(result);
        //提取所需部分的xml信息    methodResponse,method表示不同方法的不同xml节点
        return xmlJSONObj.getJSONObject("SOAP-ENV:Envelope").getJSONObject("SOAP-ENV:Body").getJSONObject(methodResponse)
                .getJSONObject(method).get("content").toString();
    }


    //查询订单信息
    @GetMapping("selectOrder")
    @ApiOperation("忽略Token验证测试")
    public R selectOrder(Card card1) {

        OrderQueryResultEntity orderQueryResultEntity = new OrderQueryResultEntity();
        OrderQueryBody orderQueryBody = new OrderQueryBody();
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setAc(AC);
        orderQuery.setPw(PW);
        //这里是提交订单后返回的票付通订单号
        orderQuery.setPftOrdernum("68975169014976");
        orderQueryBody.setOrderQuery(orderQuery);
        orderQueryResultEntity.setBody(orderQueryBody);
        String strXml = JAXBXmlUtil.convertToXml(orderQueryResultEntity);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> formEntity = new HttpEntity<>(strXml, httpHeaders);
        String result = restTemplate.postForObject(PFT_URL, formEntity, String.class);
        System.out.println("pft OrderQuery result:" + result);
        String orderQueryDataResultXml = getPftResultXml(result, "ns1:OrderQueryResponse", "OrderQuery");
        String orderQueryDataResultJson = XML.toJSONObject(orderQueryDataResultXml).toString();
        System.out.println("查询的订单是：" + orderQueryDataResultJson);

        return R.ok("完全ok");
    }
}
